<?php
/**
 * Created by PhpStorm.
 * User: stupboy
 * Date: 2018/2/7
 * Time: 22:54
 */

namespace app\api\behavior;
use app\base\service\Dayu;
use app\base\service\Redis;
use think\Db;
use app\base\logic;
use think\Exception;

/**
 * Class 司机操作通知乘客行为
 * @package app\api\behavior
 */
class Order
{
    public $push;

    public function __construct()
    {
        $this->push = new logic\Push();
    }

    public function useCar(&$params){
        $this->sendMsg($params,'您有一个审核订单，请您注意查收',1,1);
    }

    /**
     * 接单
     * @param $params
     */
    public function receOrder(&$params){
        // 生成订单轨迹图 用于轨迹预警
        $redis = Redis::getInstance();
        $redis->push('order_route',$params);
        
        $this->sendMsg($params,'订单已派车',3);
        $field = 'a.order_no,a.order_id,a.order_state,a.order_type,a.use_type,a.booking_type,a.order_time,a.car_type_id,a.area_id,a.driver_id,';
        $field.= 'b.from_addr departure,b.from_lon,b.from_lat,b.to_addr destination,b.to_lon,b.to_lat,b.plan_time,b.call_time';
        $field.= ',c.type,c.car_type,d.law_type,d.prop';
        try{
            $order = Db::name('order')->alias('a')
                ->join('order_gps b','a.order_id = b.order_id','left')
                ->join('car_type c','a.car_type_id = c.car_type_id','left')
                ->join('company d','d.company_id = a.company_id')
                ->where('a.order_id',$params)->field($field)->find();
        }catch (Exception $e){
            return;
        }
        $order['action']      = 'dispatch';
        $order['order_state'] = 4;
        $temp = '您有一个指派订单，今天 %s 从 %s 到 %s ，请您注意查收！';
        $temp2= '您有一个指派包车订单，今天 %s 从 %s 出发，请您注意查收！';//包车语音内容
        $time = $order['plan_time'];
        $str  = empty($order['destination']) ? sprintf($temp2,$time,$order['departure']) : sprintf($temp,$time,$order['departure'],$order['destination']);
        $order['notice']      = $str;
        $this->sendMessageNoticeDriver($order['driver_id'],$order,$str,60);

        $this->updateOrdersTime($order['order_id']);
    }

    /**
     * 后台报价
     * @param $params 订单id
     */
    public function priceOrder(&$params){
        $this->sendMsg($params,'订单已报价',12);
    }

    /**
     * 改派
     * @param $params
     */
    public function changeDispatch(&$params){
        $this->sendMsg($params['oid'],'订单已改派',3);

        $field = 'a.order_no,a.order_id,a.order_state,a.order_type,a.use_type,a.booking_type,a.order_time,a.car_type_id,a.area_id,a.driver_id,a.passenger_id,';
        $field.= 'b.from_addr departure,b.from_lon,b.from_lat,b.to_addr destination,b.to_lon,b.to_lat,b.plan_time,b.call_time';
        $field.= ',c.type,c.car_type,d.law_type,d.prop';
        try{
            $order = Db::name('order')->alias('a')
                ->join('order_gps b','a.order_id = b.order_id','left')
                ->join('car_type c','a.car_type_id = c.car_type_id','left')
                ->join('company d','d.company_id = a.company_id')
                ->where('a.order_id',$params['oid'])->field($field)->find();
        }catch (Exception $e){
            return;
        }
        $order['action']      = 'dispatch';
        $order['order_state'] = 4;
        $temp = '您有一个指派订单，今天 %s 从 %s 到 %s ，请您注意查收！';
        $temp2= '您有一个指派包车订单，今天 %s 从 %s 出发，请您注意查收！';//包车语音内容
        if($order['driver_id'] == $params['driver_id']){
            $temp = '您的订单已改派，今天 %s 从 %s 到 %s ，请您注意查收！';
            $temp2= '您的包车订单已改派，今天 %s 从 %s 出发，请您注意查收！';//包车语音内容
        }
        $time = $order['plan_time'];
        $str  = empty($order['destination']) ? sprintf($temp2,$time,$order['departure']) : sprintf($temp,$time,$order['departure'],$order['destination']);
        $order['notice']      = $str;
        $this->sendMessageNoticeDriver($order['driver_id'],$order,$str,60);
        $msg['action']      = 'cancel_order';
        $msg['order_id']    = $params['oid'];
        $msg['order_state'] = 5;

        if($order['driver_id'] != $params['driver_id']) {
            $this->sendMessageNoticeDriver($params['driver_id'], $msg, '订单已改派', 60);
        }

        $this->updateOrdersTime($order['order_id']);
//        $p_msg = [
//            'order_id' => $params['oid'],
//            'action' => 'change_dispatch',
//        ];
//
//        $this->sendMessageNoticePassenger($order['passenger_id'], $p_msg, '订单已改派');
    }

    /**
     * 开始订单
     * @param $params
     */
    public function startOrder(&$params){
        $this->sendMsg($params,'司机出发',5);
    }

    /**
     * 到达出发地
     * @param $params
     */
    public function arrivalOrder(&$params){
        $this->sendMsg($params,'您好！司机已经准确到达您的出发地，请您尽快上车！',6);
    }

    /**
     * 开始订单
     * @param $params
     */
    public function goOrder(&$params){
        (new \app\api\model\Order())->checkNewException($params);// 异常检测
        $this->sendMsg($params,'司机已开始订单',7);
    }

    /**
     * 费用确认
     * @param $params
     */
    public function sureFee(&$params){
        (new \app\api\model\Order())->checkNewException($params);// 异常检测
        $this->sendMsg($params,'费用确认',9);
    }

    /**
     * 订单审核
     * @param $params
     */
    public function checkOrder(&$params){
        $this->sendMsg($params,'您的订单已经通过审批，请您注意查收！',2,1);
    }

    /**
     * 审核不通过
     * @param $params
     */
    public function rejectOrder(&$params){
        $this->sendMsg($params,'抱歉，您的订单未能通过审批，请您注意查收！',2,1);
    }

    /**
     * 乘客取消订单
     * @param $params
     */
    public function cancelOrder(&$params){
        $oid   = $params['oid'];
        $state = $params['order_state'];
        $uid   = $params['uid'];
        $field = 'driver_id,passenger_id,approval_id,order_state';
        $order = Db::name('order')->where('order_id',$oid)->field($field)->find();

        if(isset($params['is_admin']) && $params['is_admin'] === true) {
            $data = ['action'=>'cancel_order','order_id'=>$oid,'order_state'=>$state];
            $this->sendMessageNoticePassenger($order['passenger_id'],$data,'订单已被管理员取消');
            $this->sendMessageNoticeDriver($order['driver_id'],$data,'订单已被管理取消');

        }else {
            if($order['passenger_id']==$uid){
                $data = ['action'=>'cancel_order','order_id'=>$oid,'order_state'=>$state];
                $this->sendMessageNoticeDriver($order['driver_id'],$data,'订单已被乘客取消');
            }
            if($order['approval_id']==$uid && $order['passenger_id'] != $order['approval_id']){
                $data = ['action'=>'cancel_order','order_id'=>$oid,'order_state'=>$state];
                $this->sendMessageNoticePassenger($order['passenger_id'],$data,'订单已被审核员取消');
                $this->sendMessageNoticeDriver($order['driver_id'],$data,'订单已被审核员取消');
            }
        }
    }

    public function cancelOrderDriver(&$params){
        $this->sendMsg($params,'司机已取消订单',4);
    }

    /**
     * 自动支付
     * @param $params
     */
    public function autoPay(&$params){
        $this->sendMsg($params,'您的订单自动付款成功',11);
        // 通知司机
        $did = Db::name('order')->where('order_id',$params)->value('driver_id');
        $data= ['action'=>'pay_order','order_id'=>$params];
        $this->sendMessageNoticeDriver($did,$data,'乘客已付款');
    }

    /**
     * 定时支付失败
     * @param $params
     */
    public function payError(&$params){
        $this->sendMsg($params,'您有订单需要支付',10);
    }

    /**
     * 后台 派单行为
     * @param $params
     */
    public function sendOrder(&$params){
        $field = 'a.order_id,a.order_state,a.order_type,a.use_type,a.booking_type,a.order_time,a.car_type_id,a.area_id';
        $field.= ',b.from_addr departure,b.from_lon,b.from_lat,b.to_addr destination,b.to_lon,b.to_lat,b.plan_time';
        $field.= ',a.passenger_id,a.driver_id';
        $where['a.order_id'] = $params;
        $order = Db::name('order')->alias('a')
            ->join('order_gps b','a.order_id = b.order_id','left')
            ->where($where)
            ->field($field)
            ->find();
        $order['action'] = 'send_order';
        $this->sendMsg($params,'订单已改派',3);
        // $this->sendMessageNoticePassenger($order['passenger_id'],$order,'您的订单已派车');
        $this->sendMessageNoticeDriver($order['driver_id'],$order,'系统派单，请注意查看');

        // 发送语音播报
        $order['action']      = 'dispatch';
        $temp = '您有一个指派订单，今天 %s 从 %s 到 %s ，请您注意查收！';
        $temp2= '您有一个指派包车订单，今天 %s 从 %s 出发，请您注意查收！';//包车语音内容
        if($order['driver_id'] == $params['driver_id']){
            $temp = '您的订单已改派，今天 %s 从 %s 到 %s ，请您注意查收！';
            $temp2= '您的包车订单已改派，今天 %s 从 %s 出发，请您注意查收！';//包车语音内容
        }
        $time = $order['plan_time'];
        $str  = empty($order['destination']) ? sprintf($temp2,$time,$order['departure']) : sprintf($temp,$time,$order['departure'],$order['destination']);
        $order['notice']      = $str;
        $this->sendMessageNoticeDriver($order['driver_id'],$order,$str,60);
        $this->updateOrdersTime($order['order_id']);
    }

    public function payOrder(&$params){
        $did = Db::name('order')->where('order_id',$params)->value('driver_id');
        $data= ['action'=>'pay_order','order_id'=>$params];
        $this->sendMessageNoticeDriver($did,$data,'乘客已付款');
    }



    public function sendMsg($oid=0,$notice='',$action=0,$type=0){
        $field = 'a.order_id,a.order_no,a.order_state,b.from_addr,b.from_lon,b.from_lat,a.passenger_phone,car.number car_number,b.plan_time,passenger_name,';
        $field.= 'b.to_addr,b.to_lon,b.to_lat,e.push_user_id,f.push_user_id approval_push_id,g.name driver_name,g.phone driver_phone';
        $field.= ',d.phone approval_phone';
        try{
            $order = Db::name('order')->alias('a')
                ->join('order_gps b','a.order_id = b.order_id','left')
                ->join('passenger c','c.passenger_id = a.passenger_id','left')
                ->join('passenger d','d.passenger_id = a.approval_id','left')
                ->join('push_bind e','c.user_id = e.user_id and e.use_type = 2','left')
                ->join('push_bind f','d.user_id = f.user_id and f.use_type = 2','left')
                ->join('driver g','a.driver_id = g.driver_id','left')
                ->join('car' ,'a.car_id = car.car_id','left')
                ->where('a.order_id',$oid)
                ->field($field)
                ->find();
        }catch (Exception $e){
            $order = [];
        }
        if(empty($order)){
            return;
        }
        $data['order_id']    = $oid;
        $data['order_no']    = $order['order_no'];
        $data['order_state'] = $order['order_state'];
        $data['from_addr']   = $order['from_addr'];
        $data['from_lon']    = $order['from_lon'];
        $data['from_lat']    = $order['from_lat'];
        $data['to_addr']     = $order['to_addr'];
        $data['to_lon']      = $order['to_lon'];
        $data['to_lat']      = $order['to_lat'];
        $data['message']     = $notice;
        $data['action']      = $action;
        $data['show_message']= $type;
        in_array($action,[1,2,6]) && $data['speak'] = 1;
        if($action==3){//接单动作添加短信推送
            $sms = new logic\Sms();
            // 您已成功接受订单${order},您的车辆车牌号：${car}，出发地：${from}，目的地：${to} ，出发时间：${time} 。乘客姓名：${name}
            $toAddress = empty($order['to_addr']) ? '包车' : $order['to_addr'];
            $smsData = [
                'order'=>$order['order_no'],
                'car'=>$order['car_number'],
                'from'=>$order['from_addr'],
                'to'=>$toAddress,
                'time'=>$order['plan_time'],
                'name'=>maskName($order['passenger_name'])
            ];
            $sms->addToList($order['driver_phone'],$smsData,'SMS_130926256');
            // 您申请的${time}从${from}至${to}的用车订单已派车,司机:${driver}，电话：${tel} ，车牌：${car}。祝您用车愉快。
            $smsData = [
                'time'=>$order['plan_time'],
                'from'=>$order['from_addr'],
                'to'=>$toAddress,
                'driver'=>maskName($order['driver_name']),
                'tel'=>$order['driver_phone'],
                'car'=>$order['car_number']
            ];
            $sms->addToList($order['passenger_phone'],$smsData,'SMS_130911261');
        }
        // 审核人不是自己的时候发送短信
        if($action==1){
            $sms = new logic\Sms();
            $smsData = [
                'name'=>$order['passenger_name'],
                'phone'=>$order['passenger_phone']
            ];
            $sms->addToList($order['approval_phone'],$smsData,'SMS_138060054',2);
        }
        if($data['order_state']==1){
            $sign            = $order['approval_push_id'];
        }else{
            $sign            = $order['push_user_id'];
        }
        if(!empty($sign)){
            $msg             = json_encode($data);
            $this->push->pushPassenger([$sign],$msg,$notice);
        }
    }

    public function sendNotice($oid=0){
        $info = Db::name('order')->alias('a')
            ->join('passenger b','a.passenger_id = b.passenger_id','left')
            ->join('push_bind c','b.user_id = c.user_id and c.use_type = 2')
            ->where('order_id',$oid)
            ->field('a.order_state,c.push_user_id,a.order_id')
            ->find();
        if(empty($info)){
            return;
        }
        $sign = $info['push_user_id'];
        $msg  = $info['order_state'] == 2 ? '订单申请通过审核' : '订单申请被驳回';
        if(!empty($sign)){
            $this->push->pushPassengerNotice([$sign],$msg);
            $this->push->pushPassenger([$sign],json_encode($info),$msg);
        }
    }

    public function sendMessageNoticePassenger($pid=0,$msg=[],$notice=''){
        $pushId = Db::name('passenger')->alias('a')
            ->join('push_bind b','a.user_id = b.user_id and b.use_type = 2')
            ->where('a.passenger_id',$pid)
            ->value('push_user_id');
        $this->push->pushPassenger([$pushId],json_encode($msg),$notice);
    }

    public function sendMessageNoticeDriver($did=0,$msg=[],$notice='',$expire=86400){
        $pushId = Db::name('driver')->alias('a')
            ->join('push_bind b','a.user_id = b.user_id and b.use_type = 1')
            ->where('a.driver_id',$did)
            ->value('push_user_id');
        $redis = Redis::getInstance();
        $key       = $did.'_push';
        $msgNotice = [
            'notice'=>$notice,
            'msg'=>$msg,
            'time'=>time()
        ];
        if(isset($msg['action']) && $msg['action']=='dispatch'){
            $redis->set($key,json_encode($msgNotice));
        }
        $this->push->pushDriver([$pushId],json_encode($msg),$notice,$expire);
    }

    /**
     * 更新接单时间
     * @param $order_id
     * @return mixed
     */
    private function updateOrdersTime($order_id){
        $data = [
            'orders_time' => date('Y-m-d H:i:s'),
            'order_id' => $order_id,
        ];

        return Db::name('order')->update($data);
    }
}